import type {AxiosError, AxiosRequestConfig, AxiosResponse} from 'axios';
import axios from 'axios';
import {API, STORAGE_KEYS} from '../constants';
import {refreshToken} from './auth';
import {message} from 'antd';
import type {
    AnalyticsData,
    ApiResponse,
    AuthResponse,
    DashboardData,
    EventDetailsData,
    EventsData,
    MetadataData,
    MetadataDetailsData,
    ReportData,
    UserData,
    UsersListResponse
} from '../types';
import type { 
    SystemResourceData, 
    ServiceStatus, 
    LogEntry, 
    NetworkStats,
    StorageVolume,
    DatabaseStats,
    SystemMonitorData
} from './systemMonitor';

const api = axios.create({
    baseURL: API.BASE_URL,
    headers: {
        'Content-Type': 'application/json',
    },
});

/**
 * 通用请求方法，返回ApiResponse<T>类型的响应
 * @param method 请求方法
 * @param url 请求地址
 * @param config 请求配置
 * @returns Promise<ApiResponse<T>>
 */
export async function request<T = any>(
    method: 'get' | 'post' | 'put' | 'delete',
    url: string,
    config: {
        params?: Record<string, any>;
        data?: any;
        headers?: Record<string, any>;
        showErrorMessage?: boolean;
    } = {}
): Promise<ApiResponse<T>> {
    const {params, data, headers, showErrorMessage = true} = config;

    try {
        const response = await api.request<ApiResponse<T>>({
            method,
            url,
            params,
            data,
            headers
        });

        // 如果success为false且需要显示错误消息
        if (!response.data.success && showErrorMessage && response.data.message) {
            message.error(response.data.message);
        }

        return response.data;
    } catch (error: any) {
        // 处理错误
        const errorMessage = error.response?.data?.message || error.message || '请求失败';
        if (showErrorMessage) {
            message.error(errorMessage);
        }

        // 返回一个错误的ApiResponse
        return {
            success: false,
            message: errorMessage,
            data: null
        };
    }
}

// 便捷方法
export const get = <T = any>(url: string, params?: Record<string, any>, config?: Omit<Parameters<typeof request>[2], 'params'>) => {
    return request<T>('get', url, {...config, params});
};

export const post = <T = any>(url: string, data?: any, config?: Omit<Parameters<typeof request>[2], 'data'>) => {
    return request<T>('post', url, {...config, data});
};

export const put = <T = any>(url: string, data?: any, config?: Omit<Parameters<typeof request>[2], 'data'>) => {
    return request<T>('put', url, {...config, data});
};

export const del = <T = any>(url: string, params?: Record<string, any>, config?: Omit<Parameters<typeof request>[2], 'params'>) => {
    return request<T>('delete', url, {...config, params});
};

// 全局错误处理函数
export const handleApiError = (error: any, defaultMessage = '操作失败') => {
    // 如果是API返回的错误（success为false）
    if (error.isApiError) {
        // 显示错误消息
        message.error(error.message || defaultMessage);
        console.error('API错误:', error.message);
        return error.message || defaultMessage;
    }

    // 如果是HTTP错误
    if (axios.isAxiosError(error)) {
        const axiosError = error as AxiosError;
        if (axiosError.response?.data && typeof axiosError.response.data === 'object') {
            const responseData = axiosError.response.data as any;
            if (responseData.message) {
                message.error(responseData.message);
                console.error('HTTP错误:', responseData.message);
                return responseData.message;
            }
        }
        message.error(axiosError.message || defaultMessage);
        console.error('请求错误:', axiosError.message);
        return axiosError.message || defaultMessage;
    }

    // 其他错误
    message.error(error?.message || defaultMessage);
    console.error('未知错误:', error);
    return error?.message || defaultMessage;
};

// 请求拦截器
api.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem(STORAGE_KEYS.JWT_TOKEN);

        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }

        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
api.interceptors.response.use(
    <T>(response: AxiosResponse<ApiResponse<T>>) => {
        // 直接返回响应，让request方法处理数据和错误
        return response;
    },
    async (error) => {
        // 处理HTTP错误
        const originalRequest = error.config as AxiosRequestConfig & { _retry?: boolean };

        // 如果错误不是401或者该请求已经尝试过刷新令牌，则拒绝
        if (!error.response || error.response.status !== 401 || originalRequest._retry) {
            return Promise.reject(error);
        }

        // 尝试刷新令牌
        try {
            const newToken = await refreshToken();
            if (newToken) {
                // 更新授权头
                if (originalRequest.headers) {
                    originalRequest.headers.Authorization = `Bearer ${newToken}`;
                }
                // 重试原始请求
                originalRequest._retry = true;
                return axios(originalRequest);
            } else {
                // 刷新失败，清除认证数据并重定向到登录页
                localStorage.removeItem(STORAGE_KEYS.JWT_TOKEN);
                localStorage.removeItem(STORAGE_KEYS.REFRESH_TOKEN);
                localStorage.removeItem(STORAGE_KEYS.IS_AUTHENTICATED);
                localStorage.removeItem(STORAGE_KEYS.USER);
                window.location.href = '/login';
                return Promise.reject(error);
            }
        } catch (refreshError) {
            // 刷新失败，清除认证数据并重定向到登录页
            localStorage.removeItem(STORAGE_KEYS.JWT_TOKEN);
            localStorage.removeItem(STORAGE_KEYS.REFRESH_TOKEN);
            localStorage.removeItem(STORAGE_KEYS.IS_AUTHENTICATED);
            localStorage.removeItem(STORAGE_KEYS.USER);
            window.location.href = '/login';
            return Promise.reject(refreshError);
        }
    }
);

// 认证相关API
export const login = <T = AuthResponse>(username: string, password: string) => {
    return post<T>(API.AUTH.LOGIN, {username, password});
};

export const logout = <T = null>() => {
    return post<T>(API.AUTH.LOGOUT);
};

export const getCurrentUser = <T = UserData>() => {
    return get<T>(API.AUTH.CURRENT_USER);
};

// 用户管理API
export const getUsers = (params: {
    page: number;
    pageSize: number;
    searchText: string;
    role: string | undefined;
    status: string | undefined
}) => {
    return get<UsersListResponse>(API.USERS.LIST, params);
};

export const getUser = <T = UserData>(username: string) => {
    return get<T>(API.USERS.DETAIL(username));
};

export const createUser = (userData: any) => {
    return post<UserData>(API.USERS.CREATE, userData);
};

export const updateUser =  (username: string, userData: any) => {
    return put<UserData>(API.USERS.UPDATE(username), userData);
};

export const deleteUser = <T = null>(username: string) => {
    return del<T>(API.USERS.DELETE(username));
};

// 仪表盘API
export const getDashboardData = () => {
    return get<DashboardData>(API.DASHBOARD.DATA);
};

// 事件API
export const getEvents = (params: {
    page?: number;
    pageSize?: number;
    category?: string;
    name?: string;
    startDate?: string;
    endDate?: string;
    groupBy?: string;
    metadataId?: string;
}) => {
    return get<EventsData>(API.EVENTS.LIST, params);
};

export const getEventById = (id: string) => {
    return get<EventDetailsData>(API.EVENTS.DETAIL(id));
};

export const deleteEvent = <T = null>(id: string) => {
    return del<T>(API.EVENTS.DELETE(id));
};

export const bulkDeleteEvents = <T = any>(ids: string[]) => {
    return post<T>(API.EVENTS.BULK_DELETE, {ids});
};

// 元数据API
export const getMetadata = (params: {
    page?: number;
    pageSize?: number;
}) => {
    return get<MetadataData>(API.METADATA.LIST, params);
};

/**
 * 获取元数据详情
 * @param id 元数据ID
 * @returns 包含元数据详情、格式化时间和关联事件数量的响应
 */
export const getMetadataById = (id: string) => {
    return get<MetadataDetailsData>(API.METADATA.DETAIL(id));
};

// 报表API
export const getReportData = (params: {
    timeRange?: number;
    category?: string;
    groupBy?: string;
}) => {
    return get<ReportData>(API.REPORTS.DATA, params);
};

// 分析API
export const getAnalyticsData = (params: {
    timeRange?: number;
    category?: string;
    analysisType?: 'trend' | 'comparison' | 'forecast' | 'correlation';
}) => {
    return get<AnalyticsData>(API.ANALYTICS.DATA, params);
};

// 遥测直接API
export const getTelemetryStatus = <T = any>() => {
    return get<T>(API.TELEMETRY.STATUS);
};

export const submitTelemetry = <T = any>(data: any) => {
    return post<T>(API.TELEMETRY.SUBMIT, data);
};

export const getTelemetryEvents = <T = any>(limit?: number) => {
    return get<T>(API.TELEMETRY.EVENTS, {limit});
};

export const getTelemetryMetadata = <T = any>(limit?: number) => {
    return get<T>(API.TELEMETRY.METADATA, {limit});
};

// 系统监控API
export const getSystemMonitorData = () => {
    return get<SystemMonitorData>(API.SYSTEM.ALL);
};

export const getSystemResources = () => {
    return get<SystemResourceData>(API.SYSTEM.RESOURCES);
};

export const getServiceStatuses = () => {
    return get<ServiceStatus[]>(API.SYSTEM.SERVICES);
};

export const restartService = (serviceName: string) => {
    return post(API.SYSTEM.RESTART_SERVICE(serviceName));
};

export const getSystemLogs = (limit?: number) => {
    return get<LogEntry[]>(API.SYSTEM.LOGS, { limit });
};

export const getNetworkStats = () => {
    return get<NetworkStats>(API.SYSTEM.NETWORK);
};

export const getStorageVolumes = () => {
    return get<StorageVolume[]>(API.SYSTEM.STORAGE);
};

export const getDatabaseStats = () => {
    return get<DatabaseStats>(API.SYSTEM.DATABASE);
};

export const addSystemLogEntry = (level: string, service: string, message: string) => {
    return post(API.SYSTEM.LOGS, { level, service, message });
};

export default api; 